<template>
  <a-modal
    title-align="start"
    v-model:visible="visible"
    @close="handleCancel(formRef)"
  >
    <template #title>修改密码</template>
    <a-form ref="formRef" :rules="rules" :model="form">
      <a-form-item field="password" label="密码" validate-trigger="blur">
        <a-input-password
          v-model="form.password"
          placeholder="please enter your password..."
        />
      </a-form-item>
      <a-form-item field="password2" label="确认密码" validate-trigger="blur">
        <a-input-password
          v-model="form.password2"
          placeholder="please confirm your password..."
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="visible = false">取消</a-button>
      <a-button type="primary" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, defineEmits, reactive } from 'vue';
import { updatePassward } from '@/api/user';
import { updateUserPwd } from '@/api/list';
import { Message } from '@arco-design/web-vue';
const formRef = ref<any>(null);
const form = reactive({
  password: '',
  password2: '',
});

const rules = {
  password: [
    {
      required: true,
      message: 'password is required',
    },
  ],
  password2: [
    {
      required: true,
      message: 'password is required',
    },
    {
      validator: (value: any, cb: any) => {
        if (value !== form.password) {
          cb('two passwords do not match');
        } else {
          cb();
        }
      },
    },
  ],
};

const visible = ref(false);
const curId = ref('');
const handleClick = (val: any) => {
  visible.value = true;
  if (val && val.id) {
    curId.value = val.id;
  }
};
const emits = defineEmits(['submitFrom']);

const handleOk = async () => {
  const res = await formRef.value?.validate();
  if (!res) {
    if (!curId.value) {
       try {
        const res: any = await updatePassward({ password: form.password2 });
        if (res.code === 20000) Message.success('修改成功');
      } catch (error) {
      } finally {
        visible.value = false;
      }
    } else {
      try {
        const res: any = await updateUserPwd(curId.value,{ password: form.password2 });
        if (res.code === 20000) Message.success('修改成功');
      } catch (error) {
      } finally {
        visible.value = false;
      }
    }
  }
};
const handleCancel = (formEl: any) => {
  curId.value = '';
  formEl.resetFields();
};
defineExpose({ handleClick });
</script>

<style scoped lang="less">
.title_style {
  color: #ff7d00;
}
</style>
